const CryptoJS = require('../libs/crypto-js');
const RSA = require('../libs/wx_rsa.js')
const config = require('../config.js')
var app = getApp();


/**
 * rsa加密
 * @param {} message 
 */

const RsaEncrypt = (message) => {
  //  console.log(message);
  var encrypt_rsa = new RSA.RSAKey();
  // console.log("ooooo");
  // console.log(config.publicKey);
  encrypt_rsa = RSA.KEYUTIL.getKey(config.publicKey);
  // console.log(encrypt_rsa);
  // console.log('加密RSA:')
  var encStr = encrypt_rsa.encrypt(message)
  // console.log("encStr：" + encStr)
  encStr = RSA.hex2b64(encStr);
  // console.log("加密结果：" + encStr)
  return encStr;
}


/**
 * rsa解密
 * @param {}} message 
 */
const RsaDecrypt = (message, privateKey) => {
  var decrypt_rsa = new RSA.RSAKey();
  decrypt_rsa = RSA.KEYUTIL.getKey(privateKey);
  var encStr = RSA.b64tohex(message);
  var decStr = decrypt_rsa.decrypt(encStr)

  return decStr;
}


/**
 * @description: AES加密方法
 * @param {type} 
 * @return: 
 */


const aesEncrypt = (message, aesKey) => {

  let iv = CryptoJS.enc.Utf8.parse(config.iv)


  let keyStr = CryptoJS.enc.Utf8.parse(aesKey)
  let ciphertext = CryptoJS.AES.encrypt(message, keyStr, {
    iv: iv,
    mode: CryptoJS.mode.CBC,
    padding: CryptoJS.pad.Pkcs7
  })
  return CryptoJS.enc.Base64.stringify(ciphertext.ciphertext)
}
/**
 * AES与后台协商加密方式
 */
const aesEncryptForToken = (message, aesKey) => {
  let iv = CryptoJS.enc.Utf8.parse(config.iv)
  let keyStr = CryptoJS.enc.Utf8.parse(aesKey)
  let ciphertext = CryptoJS.AES.encrypt(message, keyStr, {
    iv: iv,
    mode: CryptoJS.mode.CBC,
    padding: CryptoJS.pad.Pkcs7
  })
  return CryptoJS.enc.Base64.stringify(ciphertext.ciphertext)
}

/**
 * 字符串转日期
 */
function stringToDate(dateStr) {
  if (dateStr) {
    var year = parseInt(dateStr.substring(0, 4));
    var month = dateStr.substring(4, 6);
    //处理月份为04这样的情况                         
    if (month.indexOf("0") == 0) {
      month = parseInt(month.substring(1));
    } else {
      month = parseInt(month);
    }
    var day = parseInt(dateStr.substring(6, 8));
    var date = new Date(year, month - 1, day);
    return date;
  } else {
    return null;
  }

}
/**
 * @description: AES解密方法
 * @param {type} 
 * @return: 
 */

const aesDecrypt = (crypted, aesKey) => {
  let keyStr = CryptoJS.enc.Utf8.parse(aesKey)
  let iv = CryptoJS.enc.Utf8.parse(config.iv)
  let decryptedData = CryptoJS.AES.decrypt(crypted, keyStr, {
    iv: iv,
    mode: CryptoJS.mode.CBC,
    padding: CryptoJS.pad.Pkcs7
  })
  // console.log(decryptedData);
  return decryptedData.toString(CryptoJS.enc.Utf8)
}

/** 
 * 脱敏
 */
function engineno(engineno) {
  return engineno.replace(/^(.{4})(?:\w+)(.{4})$/, "\$1****\$2");
}

const formatTime = date => {
  const year = date.getFullYear()
  const month = date.getMonth() + 1
  const day = date.getDate()
  const hour = date.getHours()
  const minute = date.getMinutes()
  const second = date.getSeconds()

  return [year, month, day].map(formatNumber).join('-') + ' ' + [hour, minute, second].map(formatNumber).join(':')
}

const formatNumber = n => {
  n = n.toString()
  return n[1] ? n : '0' + n
}



/**
 * toast方法
 */
function showToast(title) {
  wx.showToast({
    title: title,
    icon: 'none',
    duration: 3000
  })
}


function showModal(title, content, url) {
  wx.showModal({
    title: title,
    content: content,
    success(res) {
      if (res.confirm) {
        wx.navigateTo({
          url: url
        })
      } else if (res.cancel) {
        console.log('用户点击取消')
      }
    }
  })
}

function showLoading(title) {
  wx.showLoading({
    title: title,
    icon: 'none'
  })
}



/**
 * 更改url指定参数值
 */
function replaceQueryString(url, name, value) {
  const re = new RegExp(name + '=[^&]*', 'gi')
  return url.replace(re, name + '=' + value)
}

/**
 * 校验手机号码校验11位并第一位是1
 */
function checkPhoneNum(phoneNumber) {
  let str = /^1\d{10}$/
  if (str.test(phoneNumber)) {
    return true
  } else {
    return false
  }
}

/**
 * 
 * @param {时间过滤} timestamp 
 */
function getFormatTime(timestamp) {
  // 补全为13位
  var arrTimestamp = (timestamp + '').split('');
  for (var start = 0; start < 13; start++) {
    if (!arrTimestamp[start]) {
      arrTimestamp[start] = '0';
    }
  }
  timestamp = arrTimestamp.join('') * 1;

  var minute = 1000 * 60;
  var hour = minute * 60;
  var day = hour * 24;
  var halfamonth = day * 15;
  var month = day * 30;
  var now = new Date().getTime();
  var diffValue = now - timestamp;

  // 如果本地时间反而小于变量时间
  if (diffValue < 0) {
    return '刚刚';
  }

  // 计算差异时间的量级
  var monthC = diffValue / month;
  var weekC = diffValue / (7 * day);
  var dayC = diffValue / day;
  var hourC = diffValue / hour;
  var minC = diffValue / minute;

  // 数值补0方法
  var zero = function (value) {
    if (value < 10) {
      return '0' + value;
    }
    return value;
  };

  // 使用
  if (monthC > 12) {
    // 超过1年，直接显示年月日
    return (function () {
      var date = new Date(timestamp);
      return date.getFullYear() + '年' + zero(date.getMonth() + 1) + '月' + zero(date.getDate()) + '日';
    })();
  } else if (monthC >= 1) {
    return parseInt(monthC) + "月前";
  } else if (weekC >= 1) {
    return parseInt(weekC) + "周前";
  } else if (dayC >= 1) {
    return parseInt(dayC) + "天前";
  } else if (hourC >= 1) {
    return parseInt(hourC) + "小时前";
  } else if (minC >= 1) {
    return parseInt(minC) + "分钟前";
  }
  return '刚刚';
};

function throttle(fn, gapTime) {
  if (gapTime == null || gapTime == undefined) {
    gapTime = 1500
  }

  let _lastTime = null
  console.log(!_lastTime)
  return function () {
    let _nowTime = +new Date()
    if (_nowTime - _lastTime > gapTime || !_lastTime) {
      fn.apply(this, arguments)
      _lastTime = _nowTime
    }
  }
}

//强制保留两位小数
function toDecimal(x) {
  var f = parseFloat(x);

  //isNaN() 函数用于检查其参数是否是非数字值,如果 x 是特殊的非数字值 NaN（或者能被转换为这样的值），返回的值就是 true。如果 x 是其他值,则返回 false。

  if (isNaN(f)) {
    return false;
  }
  var f = Math.round(x * 100) / 100; //round() 方法可把一个数字舍入为最接近的整数
  var s = f.toString();
  var rs = s.indexOf('.');
  if (rs < 0) {
    rs = s.length;
    s += '.';
  }
  while (s.length <= rs + 2) {
    s += '0';
  }
  return s;
}

function Money(value) {
  var result = "";
  //将证书部分和小数部分分开
  var valueParts = value.split(".");
  var mostSignificationDigit = valueParts[0].length - 1; // 最高有效数字位，默认为个位  
  var intervalOfDigit = 0; // 逗号之间的位数（从零累计）  
  var digit, countOfSignificationDigit;

  //按位取出整数部分的值
  //如果不加下面这句话，低版本浏览器可能无法处理整数部分
  var roundNum = valueParts[0].split("");

  for (var i = valueParts[0].length - 1; i >= 0; i--) {
    digit = roundNum[i];
    result = digit + result;
    if (digit != "0") {
      mostSignificationDigit = i;
    }
    //每三位添加逗号
    if (3 == ++intervalOfDigit) {
      result = "," + result;
      intervalOfDigit = 0;
    }
    //alert(digit);
    //alert(result);
  }
  if (mostSignificationDigit == -1) {
    result = "0";
  } else {
    countOfSignificationDigit = valueParts[0].length - mostSignificationDigit;
    if (countOfSignificationDigit > 3) {
      result = result.substring(result.length - (countOfSignificationDigit % 3 == 0 ? countOfSignificationDigit / 3 - 1 : countOfSignificationDigit / 3) - countOfSignificationDigit);
    } else {
      result = result.substring(result.length - countOfSignificationDigit);
    }
  }
  if (valueParts.length == 2) {
    result += ".";
    var temp = 2 - valueParts[1].length; // 是否需要补0  
    for (var i = 0; i < temp; i++) {
      valueParts[1] += "0"
    }
    result += valueParts[1].substring(0, 2);
  } else {
    result += ".00";
  }
  return result;
}
//保留小数后几位（不四舍五入）
function formatDecimal(num, decimal) {
  num = num.toString();
  var index = num.indexOf('.');
  if (index !== -1) {
    num = num.substring(0, decimal + index + 1)
  } else {
    num = num.substring(0)
  }
  return parseFloat(num).toFixed(decimal)
}
//时间字符串格式化yyyy年MM月dd日,只使用20160506这种格式的日期
const formate = function (e) {
  let year = e.substring(0, 4)
  let month = e.substring(4, 6)
  let day = e.substring(6, 8)
  return year + "年" + month + "月" + day + "日";
}

//时间字符串格式化为yyyy-MM-dd,只使用20160506这种格式的日期 
const formate1 = function (e) {
  let year = e.substring(0, 4)
  let month = e.substring(4, 6)
  let day = e.substring(6, 8)
  return year + "-" + month + "-" + day;
}

/**
 * 获取随机key
 * @param {*} e 
 */
const getKey = function (size) {
  let seed = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k',
    'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z', '0',
    '1', '2', '3', '4', '5', '6', '7', '8', '9'
  ];
  let keyNum = '';
  for (let i = 0; i < size; i++) {
    let j = Math.floor(Math.random() * seed.length);
    keyNum += seed[j];
  }
  return keyNum;
}
//时间比较
function isBeOverdue(nowDate, date) {
  var nowTime = nowDate;

  if (date.length <= 6) {
    nowTime = nowTime.substring(8)
    if (parseFloat(date) <= parseFloat(nowTime)) {
      return true;
    } else {
      return false;
    }
  } else if (date.length <= 8 && date.length > 6) {
    nowTime = nowTime.substring(0, 8)
    if (parseFloat(date) <= parseFloat(nowTime)) {
      return true;
    } else {
      return false;
    }
  } else {
    // var nowTime = [year, month, day, hour, minute, second].map(formatNumber).join('');
    if (parseFloat(date) <= parseFloat(nowTime)) {
      return true;
    } else {
      return false;
    }
  }
}

//校验不超过多少个月
function checkTime(startTime, endTime, num) {
  var time1 = new Date(startTime.substring(0, 8)).getTime();
  var time2 = new Date(endTime.substring(0, 8)).getTime();
  if (parseInt(Math.abs(time1 - time2) / 1000 / 60 / 60 / 24) > num) {
    return true;
  }
  return false;
}

function checkImgUrl(imageUrl) {
  if (imageUrl && imageUrl.length > 0 && imageUrl.indexOf('http') == -1) {

    return (config.picurl + imageUrl)

  }
  return imageUrl;
}

function add0(m) {
  return m < 10 ? '0' + m : m
}

//时间格式 2007-09-01
function MDHMTime(shijianchuo) {
  //shijianchuo是整数，否则要parseInt转换
  var time = new Date(parseInt(shijianchuo));
  var y = time.getFullYear();
  var m = time.getMonth() + 1;
  var d = time.getDate();
  var h = time.getHours();
  var mm = time.getMinutes();
  var s = time.getSeconds();
  return y + '-' + add0(m) + '-' + add0(d);
}

/**
 * 跳转到处理参数后的URL
 */

function jumpFixedUrl(url) {
  console.log(`jumpFixedUrl:${url}`);
  if (isEmpty(url)) {
    showToast('跳转URL不能为空')
  } else {
    wx.navigateTo({
      url: `/pages/fixedUrlWebview/fixedUrlWebview?url=${encodeURIComponent(url)}`,
    })
  }
}

/**
 * 通过活动id,跳转到
 * @param {活动ID} actId 
 */
function jumpNormalAct(actId) {
  if (isEmpty(actId)) {
    showToast('出错了，活动ID不能为空')
  } else {
    wx.navigateTo({
      url: `/pages/activityH5/activityH5?activityId=${actId}`
    })
  }
}

/**
 * 解析全部的url参数
 */
export function getUrlParamObject(url) {
  var obj = {};
  if (!isEmpty(url)) {
    var search = url.substring(url.lastIndexOf("?") + 1);
    var reg = /([^?&=]+)=([^?&=]*)/g;
    search.replace(reg, function (rs, $1, $2) {
      var name = decodeURIComponent($1);
      var val = decodeURIComponent($2);
      val = String(val);
      obj[name] = val;
      return rs;
    });
  }
  return obj;
}

/**
 * 按照指定字段升序排序
 */
export function compareAesc(propertyName) {
  return function (object1, object2) {
    var value1 = object1[propertyName];
    var value2 = object2[propertyName];
    if (value2 > value1) {
      return -1;
    } else if (value2 < value1) {
      return 1;
    } else {
      return 0;
    }
  }
}

// 获取当前的时间戳
export function generateTimeReqestNumber() {
  var date = new Date();
  var currentTime = date.getFullYear().toString() + addZero(date.getMonth() + 1) + addZero(date.getDate()) + addZero(date.getHours()) + addZero(date.getMinutes()) + addZero(date.getSeconds())
  return currentTime
}

// 补零
export function addZero(n) {
  return n < 10 ? '0' + n : n
}

// 格式化ocr返回信息为小程序识别的标签
export function processString(inputString) {
  // 1. 替换 "<view>" 为空字符串 (使用正则表达式)
  const stringWithoutViewStart = inputString.replace(/<view>/g, "");
  // 2. 替换 "</view>" 为逗号 (使用正则表达式)
  const stringWithComma = stringWithoutViewStart.replace(/<\/view>/g, ",");
  const stringWithCommaTemp = stringWithComma.replace(/'/g, "")
  // 3. 使用逗号拆分为数组
  const stringArray = stringWithCommaTemp.split(",");
  // 4. 去除数组中的空字符串 (可选，如果需要)
  const filteredArray = stringArray.filter(item => item !== "");
  return filteredArray;
}

export function timestampToDate(timestamp) {
  const date = new Date(timestamp);
  // 获取年、月、日、时、分、秒
  const year = date.getFullYear();
  const month = date.getMonth() + 1; // 月份从 0 开始，所以需要加 1
  const day = date.getDate();
  const hours = date.getHours();
  const minutes = date.getMinutes();
  const seconds = date.getSeconds();
  // 格式化输出
  const formattedDate = `${year}-${month.toString().padStart(2, '0')}-${day.toString().padStart(2, '0')} ${hours.toString().padStart(2, '0')}:${minutes.toString().padStart(2, '0')}:${seconds.toString().padStart(2, '0')}`;
  return formattedDate

}

export function arrayOrderByColumn(array, order) {
  // 创建一个映射来快速查找每个name的索引
  const orderMap = {};
  order.forEach((name, index) => {
      orderMap[name] = index;
  });

  // 排序
  const result= array.sort((a, b) => {
      const indexA = orderMap[a.name];
      const indexB = orderMap[b.name];
      
      // 可能存在某些name不在order中
      return (indexA !== undefined ? indexA : Infinity) - (indexB !== undefined ? indexB : Infinity);
  });
  return result
}

export function checkCurrentTime() {
  // 获取当前时间
  const now = new Date();
  const hour = now.getHours();

  // 判断是否在目标时间段内（0-7点或19-24点）
  const isTargetTime = (hour >= 0 && hour < 7) || (hour >= 19 && hour <= 23);
  const flash = isTargetTime ? 'on' : 'off'
  // 更新页面数据
  return flash
}

export function findKeyMappingValueByobject(obj, column) {
  console.log('obj' , typeof obj)
  console.log('column', column)
  // 辅助函数，用于递归查找
  function search(obj) {
      if (typeof obj !== 'object' || obj === null) {
          return false;
      }
      
      for (const key in obj) {
          if (key.includes(column)) { // 找到了目标key
              const value = obj[key];
              // 检查value类型，并返回相应的结果
              if (Array.isArray(value)) {
                  return value; // 如果是数组，直接返回
              } else if (typeof value === 'string') {
                console.log('字段格式string', column, typeof column)
                let delimiter;
                if (/、/.test(value)) {
                  console.log(1111111111111111)
                    delimiter = '、';
                } else if (/,/.test(value)) {
                  console.log(222222222222222222222222)
                    delimiter = ',';
                }
                  return value.split(delimiter); // 如果是字符串，拆分为数组返回
              } else {
                console.log('字段格式不清楚', column, typeof column)
                  return false; // 如果值既不是数组也不是字符串，返回false
              }
          } else if (typeof obj[key] === 'object') {
              // 如果是对象，则继续递归查找
              const result = search(obj[key]);
              if (result !== false) {
                  return result; // 找到值，返回结果
              }
          }
      }
      
      return false; // 如果遍历完没有找到，返回false
  }

  return search(obj); // 开始查找
}

module.exports = {
  formatTime: formatTime,
  showToast: showToast,
  showModal: showModal,
  checkPhoneNum: checkPhoneNum,
  getFormatTime: getFormatTime,
  isEmpty: isEmpty,
  MDHMTime: MDHMTime,
  checkImgUrl: checkImgUrl,
  RsaEncrypt: RsaEncrypt,
  RsaDecrypt: RsaDecrypt,
  aesEncrypt: aesEncrypt,
  aesDecrypt: aesDecrypt,
  throttle: throttle,
  toDecimal: toDecimal,
  Money: Money,
  formate: formate,
  formate1: formate1,
  getKey: getKey,
  isBeOverdue: isBeOverdue,
  formatDecimal: formatDecimal,
  engineno: engineno,
  stringToDate: stringToDate,
  checkTime: checkTime,
  returnString: returnString,
  jumpFixedUrl: jumpFixedUrl,
  jumpNormalAct: jumpNormalAct,
  getUrlParamObject: getUrlParamObject,
  uploadFile: uploadFile,
  aesEncryptForToken: aesEncryptForToken,
  replaceQueryString: replaceQueryString,
  compareAesc: compareAesc,
  showLoading: showLoading,
  generateTimeReqestNumber: generateTimeReqestNumber,
  processString: processString,
  timestampToDate: timestampToDate,
  arrayOrderByColumn: arrayOrderByColumn,
  checkCurrentTime: checkCurrentTime,
  findKeyMappingValueByobject: findKeyMappingValueByobject
}

function isEmpty(str) {
  if (Object.prototype.toString.call(str) === '[object Undefined]' || Object.prototype.toString.call(str) === '[object Null]') { //空
    return true
  } else if (Object.prototype.toString.call(str) === '[object String]' || Object.prototype.toString.call(str) === '[object Array]') { //字条串或数组
    return str.length == 0 ? true : false
  } else if (Object.prototype.toString.call(str) === '[object Object]') {
    return JSON.stringify(str) == '{}' ? true : false
  } else if (Object.prototype.toString.call(str) === '[object Number]' || Object.prototype.toString.call(str) === '[object Boolean]') {
    return false
  } else {
    return true
  }
}

/** 处理数据中undefined和null*/
function returnString(str) {
  if (this.isEmpty(str)) {
    return ''
  } else {
    return str
  }
}
/**
 * 将本地资源上传到开发者服务器，客户端发起一个 HTTPS POST 请求
 * @param {string} url 开发者服务器 url
 * @param {string} filePath 要上传文件资源的路径
 * @param {string} name 
 * @param {object} formData HTTP 请求中其他额外的 form data
 */
function uploadFile(url, filePath, name, formData = {
  openid: "test"
}) {
  return new Promise((resolve, reject) => {
    let opts = {
      url,
      filePath,
      name,
      formData,
      header: {
        'Content-Type': "multipart/form-data"
      },
      success: resolve,
      fail: reject
    };
    wx.uploadFile(opts);
  });
}